<template>
    <div class="validate-input-container pb-3">
        <!-- <input type="email" class="form-control" :class="{'is-invalid': inputRef.error}" v-model="inputRef.val" @blur="validateInput"> -->
        <input class="form-control" :class="{'is-invalid': inputRef.error}" :value="inputRef.val" @blur="validateInput" @input="updateValue" v-bind="$attrs">
        <span v-if="inputRef.error" class="invalid-feedback">{{ inputRef.message }}</span>
    </div>
</template>

<script lang="ts">
import { defineComponent, PropType, reactive } from 'vue'
import { RulesProp } from '../types/RulePropsType'
const emailReg = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/
export default defineComponent({
  name: 'ValidateInput',
  props: {
    rules: {
      type: Array as PropType<RulesProp>
    },
    modelValue: String
  },
  inheritAttrs: false, // 父组件传递的任何非 prop 属性(比如placeholder)都不会自动添加到子组件的根元素上
  setup(props, context) {
    console.log(props, 'props')
    console.log(context, 'context')
    console.log(context.attrs)
    const inputRef = reactive({
      val: props.modelValue || '',
      error: false,
      message: ''
    })
    const validateInput = () => {
      if (props.rules) {
        const allPassed = props.rules.every(rule => {
          let passed = true
          inputRef.message = rule.message
          switch (rule.type) {
            case 'required':
              passed = (inputRef.val.trim() !== '')
              break
            case 'email':
              passed = emailReg.test(inputRef.val)
              break
            default:
              break
          }
          return passed
        })
        inputRef.error = !allPassed
      }
    }
    // 键盘事件
    const updateValue = (e:Event) => {
      const targetValue = (e.target as HTMLInputElement).value
      inputRef.val = targetValue
      context.emit('update:modelValue', targetValue)
    }
    return {
      inputRef,
      validateInput,
      updateValue
    }
  }
})
</script>

<style></style>
